﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Data;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web;

namespace BAL
{
    public class Utils
    {
        #region CacheString
        public static string KEY_BOXDOATGIAI(int top, int round, int awardId, int imageWidth, int imageHeight, int pageIndex, int pageSize , int pageType)
        {
            return "BOXDOATGIAI_" + top + "_" + round + "_" + awardId + "_" + imageWidth + "_" + imageHeight + "_" + pageIndex + "_" + pageSize + "_" + pageType;
        }
        public static string KEY_BOXDOATGIAI_CONT(int top, int round, int awardId, int imageWidth, int imageHeight, int pageIndex, int pageSize , int pageType)
        {
            return "BOXDOATGIAI_CONT_" + top + "_" + round + "_" + awardId + "_" + imageWidth + "_" + imageHeight + "_" + pageIndex + "_" + pageSize + "_" + pageType;
        }
        public static string KEY_BOXMOINHAT(int top, int round, int awardId, int imageWidth, int imageHeight, int pageIndex, int pageSize , int pageType)
        {
            return "BOXMOINHAT_" + top + "_" + round + "_" + awardId + "_" + round + "_" + awardId + "_" + imageWidth + "_" + imageHeight + "_" + pageIndex + "_" + pageSize + "_" + pageType;
        }
        public static string KEY_BOXMOINHAT_CONT(int top, int round, int awardId, int imageWidth, int imageHeight, int pageIndex, int pageSize , int pageType)
        {
            return "BOXMOINHAT_CONT_" + top + "_" + round + "_" + awardId + "_" + imageWidth + "_" + imageHeight + "_" + pageIndex + "_" + pageSize + "_" + pageType;
        }
        public static string KEY_SEARCH(string keySearch, int round, int awardId, int imageWidth, int imageHeight, int pageIndex, int pageSize , int pageType)
        {
            return "SEARCH_" + keySearch + "_" + round + "_" + awardId + "_" + imageWidth + "_" + imageHeight + "_" + pageIndex + "_" + pageSize + "_" + pageType;
        }
        public static string KEY_SEARCH_PAGE_NUM(string keySearch, int round, int awardId, int pageSize )
        {
            return "SEARCH_PAGE_NUM_" + keySearch + "_" + round + "_" + awardId + "_" + pageSize;
        }
        #endregion

        #region unicode
        public const string uniChars =
            "àáảãạâầấẩẫậăằắẳẵặèéẻẽẹêềếểễệđìíỉĩịòóỏõọôồốổỗộơờớởỡợùúủũụưừứửữựỳýỷỹỵÀÁẢÃẠÂẦẤẨẪẬĂẰẮẲẴẶÈÉẺẼẸÊỀẾỂỄỆĐÌÍỈĨỊÒÓỎÕỌÔỒỐỔỖỘƠỜỚỞỠỢÙÚỦŨỤƯỪỨỬỮỰỲÝỶỸỴÂĂĐÔƠƯ";

        public const string koDauChars =
            "aaaaaaaaaaaaaaaaaeeeeeeeeeeediiiiiooooooooooooooooouuuuuuuuuuuyyyyyAAAAAAAAAAAAAAAAAEEEEEEEEEEEDIIIIIOOOOOOOOOOOOOOOOOUUUUUUUUUUUYYYYYAADOOU";

        public static string UnicodeToKoDau(string s)
        {
            string retVal = String.Empty;
            int pos;
            for (int i = 0; i < s.Length; i++)
            {
                pos = uniChars.IndexOf(s[i].ToString());
                if (pos >= 0)
                    retVal += koDauChars[pos];
                else
                    retVal += s[i];
            }
            return retVal;
        }

        public static string UnicodeToKoDauAndGach(string s)
        {
            string strChar = "abcdefghiklmnopqrstxyzuvxw0123456789 ";
            //string retVal = UnicodeToKoDau(s);
            s = UnicodeToKoDau(s.ToLower().Trim());
            string sReturn = "";
            for (int i = 0; i < s.Length; i++)
            {
                if (strChar.IndexOf(s[i]) > -1)
                {
                    if (s[i] != ' ')
                        sReturn += s[i];
                    else if (i > 0 && s[i - 1] != ' ' && s[i - 1] != '-')
                        sReturn += "-";
                }
            }

            return sReturn;
        }

        public static string RemoveUnicode(string text)
        {
            text = HttpUtility.HtmlDecode(text);
            string[] arr1 = new string[] { "á", "à", "ả", "ã", "ạ", "â", "ấ", "ầ", "ẩ", "ẫ", "ậ", "ă", "ắ", "ằ", "ẳ", "ẵ", "ặ", "đ", "é", "è", "ẻ", "ẽ", "ẹ", "ê", "ế", "ề", "ể", "ễ", "ệ", "í", "ì", "ỉ", "ĩ", "ị", "ó", "ò", "ỏ", "õ", "ọ", "ô", "ố", "ồ", "ổ", "ỗ", "ộ", "ơ", "ớ", "ờ", "ở", "ỡ", "ợ", "ú", "ù", "ủ", "ũ", "ụ", "ư", "ứ", "ừ", "ử", "ữ", "ự", "ý", "ỳ", "ỷ", "ỹ", "ỵ", };
            string[] arr2 = new string[] { "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "d", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "i", "i", "i", "i", "i", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "u", "y", "y", "y", "y", "y", };
            for (int i = 0; i < arr1.Length; i++)
            {
                text = text.Replace(arr1[i], arr2[i]);
                text = text.Replace(arr1[i].ToUpper(), arr2[i].ToUpper());
            }
            return text.Replace(" ", "").ToLower();
        }
        #endregion

        #region Log
        public class CreateLogFiles
        {
            private string sLogFormat;
            private string sErrorTime;

            public CreateLogFiles()
            {
                //sLogFormat used to create log files format :

                // dd/mm/yyyy hh:mm:ss AM/PM ==> Log Message

                sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";

                //this variable used to create log filename format "

                //for example filename : ErrorLogYYYYMMDD

                string sYear = DateTime.Now.Year.ToString();
                string sMonth = DateTime.Now.Month.ToString();
                string sDay = DateTime.Now.Day.ToString();
                sErrorTime = sYear + sMonth + sDay;
            }
            public void ErrorLog(string sPathName, string sErrMsg)
            {
                StreamWriter sw = new StreamWriter(sPathName + "\\Error_" + sErrorTime + ".txt", true);
                sw.WriteLine(sLogFormat + sErrMsg);
                sw.Flush();
                sw.Close();
            }
            public void CacheLog(string sPathName, string sErrMsg)
            {
                StreamWriter sw = new StreamWriter(sPathName + "\\CacheLog_" + sErrorTime + ".txt", true);
                sw.WriteLine(sErrMsg);
                sw.Flush();
                sw.Close();
            }
            public void NotInCacheLog(string sPathName, string sErrMsg)
            {
                StreamWriter sw = new StreamWriter(sPathName + "\\NotInCacheLog_" + sErrorTime + ".txt", true);
                sw.WriteLine(sErrMsg);
                sw.Flush();
                sw.Close();
            }
            public void InCacheLog(string sPathName, string sErrMsg)
            {
                StreamWriter sw = new StreamWriter(sPathName + "\\InCacheLog_" + sErrorTime + ".txt", true);
                sw.WriteLine(sErrMsg);
                sw.Flush();
                sw.Close();
            }
            public void DepenCacheLog(string sPathName, string sErrMsg)
            {
                StreamWriter sw = new StreamWriter(sPathName + "\\DepenCacheLog_" + sErrorTime + ".txt", true);
                sw.WriteLine(sErrMsg);
                sw.Flush();
                sw.Close();
            }
            public void DepenNotInCacheLog(string sPathName, string sErrMsg)
            {
                StreamWriter sw = new StreamWriter(sPathName + "\\DepenNotInCacheLog_" + sErrorTime + ".txt", true);
                sw.WriteLine(sErrMsg);
                sw.Flush();
                sw.Close();
            }
            public void DepenInCacheLog(string sPathName, string sErrMsg)
            {
                StreamWriter sw = new StreamWriter(sPathName + "\\DepenInCacheLog_" + sErrorTime + ".txt", true);
                sw.WriteLine(sErrMsg);
                sw.Flush();
                sw.Close();
            }

            public void ProcessLog(string sPathName, string sErrMsg)
            {
                StreamWriter sw = new StreamWriter(sPathName + "\\ProcessLog_" + sErrorTime + ".txt", true);
                sw.WriteLine(sLogFormat + sErrMsg);
                sw.Flush();
                sw.Close();
            }
        }
        #endregion
        #region ReFormat
        public static string BuildLink(DataRow dr, int index)
        {
            return BuildNewsURL(dr[Const.Images.Name].ToString(), dr[Const.Images.ImageId].ToString(), index);
        }

        public static string BuildNewsURL(string Name, string ImageId, int index)
        {
            string newsURLFormat = "/{0}-i{1}id{2}.htm";
            string news_url = string.Format(newsURLFormat, UnicodeToKoDauAndGach(Name).Replace("\"", "").Replace("'", ""), ImageId, index);
            return news_url;
        }

        public static string ThumbImage(DataRow dr, int imageWidth, int imageHeight,int pageType)
        {
            string Image = string.Empty;
            if (pageType == 2) // trang List
            {
                if (!string.IsNullOrEmpty(dr[Const.Images.ImgThumbList].ToString()))
                {
                    string ImageFormat = "<img src=\"{0}\" alt=\"{1}\" title=\"{1}\" />";
                    Image = string.Format(ImageFormat, dr[Const.Images.ImgThumbList].ToString(), string.Empty);

                }
            }
            else
            {
                if (!string.IsNullOrEmpty(dr[Const.Images.ImgThumb].ToString()))
                {
                    string ImageFormat = "<img src=\"{0}\" alt=\"{1}\" title=\"{1}\" />";
                    Image =  string.Format(ImageFormat, dr[Const.Images.ImgThumb].ToString(), string.Empty);

                }
                else
                {
                    // string ImageFormat = "<img src=\"/Services/CropImages.aspx?src={0}&width={2}&height={3}\" alt=\"{1}\" title=\"{1}\" width=\"" + imageWidth + "px\" />";
                    string ImageFormat = "<img src=\"/Services/ResizeImage.aspx?url={0}&width={2}\" alt=\"{1}\" title=\"{1}\" width=\"" + imageWidth + "px\" />";
                    Image =  string.Format(ImageFormat, dr[Const.Images.Img].ToString(), string.Empty, imageWidth);
                }
            }

            return Image;
        }

        public static DataTable ReFormatTable(DataTable dt, int imageWidth, int imageHeight,int pageType)
        {
            dt.Columns.Add(Const.Images.IMAGEURL);
            dt.Columns.Add(Const.Images.Url);
            foreach (DataRow dr in dt.Rows)
            {
                dr[Const.Images.IMAGEURL] = ThumbImage(dr, imageWidth, imageHeight, pageType);
                dr[Const.Images.Url] = BuildLink(dr, 0);
            }
            dt.AcceptChanges();
            return dt;
        }

        public static string RemoveHTMLTag(string htmlString)
        {
            string pattern = @"(<[^>]+>)";
            string text = System.Text.RegularExpressions.Regex.Replace(htmlString, pattern, string.Empty);
            return text;
        }

        #endregion
        #region VietNamDate
        public static string VietNamDateHaveDayOfWeek(string date)
        {

            DateTime dt = new DateTime();
            try
            {
                dt = Convert.ToDateTime(date);
            }
            catch { dt = DateTime.Now; }
            string t = dt.DayOfWeek.ToString();
            string ngay = "";
            switch (t.ToLower())
            {
                case "monday":
                    ngay = "Thứ Hai";
                    break;
                case "tuesday":
                    ngay = "Thứ Ba";
                    break;
                case "wednesday":
                    ngay = "Thứ Tư";
                    break;
                case "thursday":
                    ngay = "Thứ Năm";
                    break;
                case "friday":
                    ngay = "Thứ Sáu";
                    break;
                case "saturday":
                    ngay = "Thứ Bảy";
                    break;
                case "sunday":
                    ngay = "Chủ Nhật";
                    break;
            }

            return ngay + ", " + VietNamDateFormated(dt, "dd/MM/yyyy HH:mm");
        }
        public static string VietNamDate(string strDate, string DateTimeFormat)
        {
            DateTime date = new DateTime();
            try
            {
                date = Convert.ToDateTime(strDate);
            }
            catch { }
            return VietNamDateFormated(date, DateTimeFormat);
        }
        public static string VietNamDateFormated(DateTime dt, string DateTimeFormat)
        {
            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
            System.Globalization.DateTimeFormatInfo dtf = new System.Globalization.DateTimeFormatInfo();
            dtf.ShortDatePattern = "MM/dd/yyyy";
            dtf.ShortTimePattern = "HH:mm:ss tt";
            ci.DateTimeFormat = dtf;
            System.Threading.Thread.CurrentThread.CurrentCulture = ci;

            return dt.ToString(DateTimeFormat);
        }
        /// <summary>
        /// Chuyen ngay viet ve ngay anh
        /// </summary>
        /// <param name="strDate">ngay viet "28/08/2008"</param>
        /// <returns>ngay anh: "08/28/2008" hoac bang "" neu co loi convert</returns>
        public static string ChangeDate(string strDate)
        {
            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
            System.Globalization.DateTimeFormatInfo dtf = new System.Globalization.DateTimeFormatInfo();
            dtf.ShortDatePattern = "MM/dd/yyyy";
            dtf.ShortTimePattern = "h:mm:ss tt";
            ci.DateTimeFormat = dtf;
            System.Threading.Thread.CurrentThread.CurrentCulture = ci;


            string strTemp;

            try
            {
                DateTime dtmDate = new DateTime();

                strTemp = Convert.ToString(strDate.Split('/')[1]) + "/" + Convert.ToString(strDate.Split('/')[0]) + "/" + Convert.ToString(strDate.Split('/')[2]);
                dtmDate = Convert.ToDateTime(strTemp);

                return dtmDate.Date.ToString("MM/dd/yyyy");

            }
            catch
            {
                return "";
            }
        }

        public static string VietNamDate(DateTime dt)
        {
            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
            System.Globalization.DateTimeFormatInfo dtf = new System.Globalization.DateTimeFormatInfo();
            dtf.ShortDatePattern = "MM/dd/yyyy";
            dtf.ShortTimePattern = "HH:mm:ss tt";
            ci.DateTimeFormat = dtf;
            System.Threading.Thread.CurrentThread.CurrentCulture = ci;

            return dt.ToString("dd/MM/yyyy") + "   " + dt.ToString("HH:mm");
        }
        public static string VietNamDate2(string date)
        {
            DateTime dt = new DateTime();
            try
            {
                dt = Convert.ToDateTime(date);
            }
            catch { }
            return VietNamDate(dt);
        }
        public static string VietNamDate3(string date, string DateTimeFormat)
        {
            DateTime dt = new DateTime();
            try
            {
                dt = Convert.ToDateTime(date);
            }
            catch { }
            return VietNamDate4(dt, DateTimeFormat);
        }
        public static string VietNamDate4(DateTime dt, string DateTimeFormat)
        {
            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
            System.Globalization.DateTimeFormatInfo dtf = new System.Globalization.DateTimeFormatInfo();
            dtf.ShortDatePattern = "MM/dd/yyyy";
            dtf.ShortTimePattern = "HH:mm:ss tt";
            ci.DateTimeFormat = dtf;
            System.Threading.Thread.CurrentThread.CurrentCulture = ci;

            return dt.ToString(DateTimeFormat);
        }
        public static string VietNamDate5(string date)
        {

            DateTime dt = new DateTime();
            try
            {
                dt = Convert.ToDateTime(date);
            }
            catch { dt = DateTime.Now; }
            string t = dt.DayOfWeek.ToString();
            string ngay = "";
            switch (t.ToLower())
            {
                case "monday":
                    ngay = "Thứ Hai";
                    break;
                case "tuesday":
                    ngay = "Thứ Ba";
                    break;
                case "wednesday":
                    ngay = "Thứ Tư";
                    break;
                case "thursday":
                    ngay = "Thứ Năm";
                    break;
                case "friday":
                    ngay = "Thứ Sáu";
                    break;
                case "saturday":
                    ngay = "Thứ Bảy";
                    break;
                case "sunday":
                    ngay = "Chủ Nhật";
                    break;
            }

            return ngay + ", " + VietNamDate4(dt, "dd/MM/yyyy HH:mm");
        }

        //28 Tháng 08, 2013 | 13:55
        public static string VietNamDate6(string date)
        {
            DateTime dt = new DateTime();
            try
            {
                dt = Convert.ToDateTime(date);
            }
            catch { dt = DateTime.Now; }

            int m = dt.Month;

            return dt.Day + " Tháng " + m + " , " + dt.Year + " | " + VietNamDateFormated(dt, "HH:mm");
        }

        #endregion
        #region Validate
        public static bool IsNumber(string _strInput)
        {
            try
            {
                Int64 _intOutPut = Convert.ToInt64(_strInput);
                return true;
            }
            catch { return false; }
        }
        public static bool isEmail(string input)
        {
            string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
             @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
             @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

            Regex re = new Regex(strRegex);
            return (re.IsMatch(input));

        }
        public static bool TableIsNotNullOrEmpty(DataTable table)
        {
            if (table != null && table.Rows.Count > 0)
            {
                return true;
            }
            return false;
        }
        #endregion

        #region Meta
        public static void AddMeta(Page _page, string strID, string MetaName, string Content)
        {
            HtmlMeta meta = new HtmlMeta();
            meta.ID = strID;
            meta.Name = MetaName;
            meta.Content = Content;
            HtmlMeta __ctlMeta = (HtmlMeta)_page.Header.FindControl(strID);
            if (__ctlMeta == null)
            {
                _page.Header.Controls.Add(meta);
            }
            else
            {
                __ctlMeta.Content = Content;
            }
        }
        public static void SetPageHeader(System.Web.UI.Page __Page, string addTitle1, string addTitle2, string addChapo)
        {
            Control __ctlTitle = (Control)__Page.Header.FindControl("Title");
            if (__ctlTitle != null)
            {
                string strTitle = "";
                if (addChapo == "") strTitle = ConfigurationManager.AppSettings["Title"] != null ? ConfigurationManager.AppSettings["Title"] : "";
                else strTitle = addChapo;
                if (__ctlTitle != null)
                {
                    string __newTitle = addTitle1 != "" ? (addTitle1 + (addTitle2 != "" ? " | " + addTitle2 : "")) + " | " + strTitle : strTitle;
                    if (__ctlTitle.Controls.Count > 0) __ctlTitle.Controls.RemoveAt(0);
                    __ctlTitle.Controls.Add(new LiteralControl(__newTitle));
                }
            }
        }
        public static void Set_Page_FB(System.Web.UI.Page __Page, string addUrl, string addTitle, string addImg, string addDes)
        {
            System.Web.UI.HtmlControls.HtmlMeta __ctlURL = __Page.Header.FindControl("OgURL") as System.Web.UI.HtmlControls.HtmlMeta;
            if (__ctlURL != null)
            {
                __ctlURL.Attributes["content"] = addUrl != null ? addUrl : "";
            }

            System.Web.UI.HtmlControls.HtmlMeta __ctlTitle = __Page.Header.FindControl("OgTitle") as System.Web.UI.HtmlControls.HtmlMeta;
            if (__ctlTitle != null)
            {
                __ctlTitle.Attributes["content"] = addTitle != null ? addTitle : "";
            }

            System.Web.UI.HtmlControls.HtmlMeta __ctlImg = __Page.Header.FindControl("OgImg") as System.Web.UI.HtmlControls.HtmlMeta;
            if (__ctlImg != null)
            {
                __ctlImg.Attributes["content"] = addImg != null ? addImg : "";
            }
            System.Web.UI.HtmlControls.HtmlMeta __ctlDesc = __Page.Header.FindControl("OgDesc") as System.Web.UI.HtmlControls.HtmlMeta;
            if (__ctlDesc != null)
            {
                __ctlDesc.Attributes["content"] = addDes != null ? addDes : "";
            }
        }

        #endregion

        public static string PreProcessSearchString(string SearchString)
        {
            string output = SearchString.Replace("'", " ").Replace("\"\"", " ").Replace(">", " ").Replace("<", " ").Replace(",", " ").Replace("(", " ").Replace(")", " ").Replace("\"", " ");
            output = System.Text.RegularExpressions.Regex.Replace(output, "[ ]+", "+");
            return output.Trim();
        }

        public static int GetCurrentRound()
        {
            int round = 0;
            DataTable dt = BussinessHelpers.GetCurrentRound();
            if (TableIsNotNullOrEmpty(dt))
            {
                round = Convert.ToInt32(dt.Rows[0][Const.AwardsWeek.RoundAwards]);
            }
            return round;
        }

        public static string VongThiStart(int vongThi)
        {
            string dt = "";
            dt = ConfigurationManager.AppSettings["ThiTuan" + vongThi + "Start"].ToString() + " 00:00:00";
            return dt;
        }

        public static string VongThiEnd(int vongThi)
        {
            string dt = "";
            dt = ConfigurationManager.AppSettings["ThiTuan" + vongThi + "End"].ToString()+" 23:59:59";
            return dt;
        }
    }
}
